<template>
  <div class="app-container">
    <!-- 主内容区域 -->
    <div class="">
      <!-- 左侧站点树 -->
      <el-row :gutter="20">
        <el-col :span="5" style="">
          <div class="left-sidebar">
            <el-card class="tree-card">
              <template #header>
                <div class="card-header">
                  <span class="card-title">站点列表</span>
                  <div class="card-actions">
                    <el-button type="primary" link @click="refreshTree">
                      <el-icon>
                        <Refresh />
                      </el-icon>
                    </el-button>
                  </div>
                </div>
              </template>
              <div class="tree-search">
                <el-input v-model="treeFilterText" placeholder="搜索站点" prefix-icon="Search" clearable />
              </div>

              <div class="tree-container">
                <el-tree ref="treeRef" :data="siteTreeData" :props="treeProps" :filter-node-method="filterNode"
                  :expand-on-click-node="false" node-key="siteId" default-expand-all highlight-current
                  @node-click="handleNodeClick">
                  <template #default="{ node, data }">
                    <div class="custom-tree-node">
                      <div class="node-content">
                        <el-icon class="node-icon">
                          <component :is="getNodeIcon(data)" />
                        </el-icon>
                        <span class="node-label">{{ data.siteName }}</span>
                        <span v-if="data.children && data.children.length > 0" class="node-count">
                          ({{ data.children.length }})
                        </span>
                      </div>
                      <div class="node-status">
                        <el-tag :type="getSiteStatusTag(data.siteStatus)" size="small" effect="light">
                          {{ getSiteStatusText(data.siteStatus) }}
                        </el-tag>
                      </div>
                    </div>
                  </template>
                </el-tree>
              </div>
            </el-card>
          </div>
        </el-col>
        <el-col :span="19">
          <!-- 右侧分屏展示区域 -->
          <div class="right-content">
            <!-- 分屏模式选择 -->
            <el-card class="mode-card">
              <div class="mode-selection">
                <div class="mode-title">分屏模式</div>
                <div class="mode-buttons">
                  <el-button-group>
                    <el-button :type="screenMode === 1 ? 'primary' : ''" @click="changeScreenMode(1)">
                      单屏
                    </el-button>
                    <el-button :type="screenMode === 4 ? 'primary' : ''" @click="changeScreenMode(4)">
                      4分屏
                    </el-button>
                    <el-button :type="screenMode === 9 ? 'primary' : ''" @click="changeScreenMode(9)">
                      9分屏
                    </el-button>
                    <el-button :type="screenMode === 16 ? 'primary' : ''" @click="changeScreenMode(16)">
                      16分屏
                    </el-button>
                  </el-button-group>
                </div>
                <div class="screen-info">
                  <span>当前显示: {{ currentDevices.length }}/{{ screenMode }} 个设备</span>
                  <el-button type="primary" link @click="autoArrange">
                    <el-icon>
                      <MagicStick />
                    </el-icon>
                    智能排布
                  </el-button>
                </div>
              </div>
            </el-card>

            <el-card>
              <!-- 分屏展示区域 -->
              <div class="screen-container" :class="`screen-mode-${screenMode}`">
                <div v-for="(device, index) in currentDevices" :key="device.deviceId" class="screen-item"
                  :class="{ active: currentDevice?.deviceId === device.deviceId }">
                  <div class="screen-header">
                    <div class="device-info">
                      <h4 class="device-name">{{ device.deviceName }}</h4>
                      <div class="device-status">
                        <el-tag :type="getDeviceStatusTag(device.deviceStatus)" size="small">
                          {{ getDeviceStatusText(device.deviceStatus) }}
                        </el-tag>
                        <el-tag :type="getAccessStatusTag(device.accessStatus)" size="small">
                          {{ getAccessStatusText(device.accessStatus) }}
                        </el-tag>
                      </div>
                    </div>
                    <div class="screen-actions">
                      <el-button type="text" size="small" @click="handleFullScreen(device)">
                        <el-icon>
                          <FullScreen />
                        </el-icon>
                      </el-button>
                      <el-button type="text" size="small" @click="handleViewDetail(device)">
                        <el-icon>
                          <View />
                        </el-icon>
                      </el-button>
                      <el-button type="text" size="small" @click="handleRemoveScreen(device)">
                        <el-icon>
                          <Close />
                        </el-icon>
                      </el-button>
                    </div>
                  </div>

                  <div class="video-container">
                    <!-- <video-player v-if="device.liveStream" :src="device.liveStream.streamUrl" class="video-player"
                :poster="getDevicePoster(device)" controls :loop="true" :volume="0.6"
                @ready="handlePlayerReady(device, $event)" @error="handlePlayerError(device, $event)" /> -->

                    <LivePlayer v-if="device.liveStream" :src="device.liveStream.streamUrl" protocol="mp4"
                      :autoplay="true" :controls="true" />

                    <div v-else class="video-placeholder">
                      <div class="placeholder-content">
                        <el-icon class="placeholder-icon">
                          <VideoCamera />
                        </el-icon>
                        <p class="placeholder-text">暂无视频流</p>
                        <el-button type="primary" size="small" @click="handleLoadStream(device)">
                          加载视频
                        </el-button>
                      </div>
                    </div>
                  </div>

                  <div class="screen-footer">
                    <div class="device-meta">
                      <span class="ip-address">{{ device.deviceIp }}</span>
                      <span class="site-name">{{ device.siteName }}</span>
                    </div>
                    <div class="live-status">
                      <el-tag v-if="device.liveStream"
                        :type="device.liveStream.streamStatus === 1 ? 'success' : 'danger'" size="small">
                        {{ device.liveStream.streamStatus === 1 ? '直播中' : '流中断' }}
                      </el-tag>
                    </div>
                  </div>
                </div>

                <!-- 空屏位 -->
                <div v-for="n in (screenMode - currentDevices.length)" :key="`empty-${n}`" class="screen-item empty"
                  @click="handleAddScreen">
                  <div class="empty-content">
                    <el-icon class="empty-icon">
                      <Plus />
                    </el-icon>
                    <p class="empty-text">点击添加设备</p>
                  </div>
                </div>
              </div>
            </el-card>

            <!-- 设备列表 -->
            <el-card class="device-list-card">
              <template #header>
                <div class="card-header">
                  <span class="card-title">设备列表</span>
                  <div class="card-actions">
                    <el-input v-model="deviceFilterText" placeholder="搜索设备" prefix-icon="Search" clearable
                      style="width: 200px" />
                  </div>
                </div>
              </template>

              <div class="device-list">
                <div v-for="device in filteredDevices" :key="device.deviceId" class="device-item"
                  :class="{ active: currentDevices.some(d => d.deviceId === device.deviceId) }"
                  @click="handleToggleDevice(device)">
                  <div class="device-main">
                    <div class="device-icon">
                      <el-icon>
                        <VideoCamera />
                      </el-icon>
                    </div>
                    <div class="device-info">
                      <div class="device-name">{{ device.deviceName }}</div>
                      <div class="device-details">
                        <span class="device-ip">{{ device.deviceIp }}</span>
                        <span class="device-site">{{ device.siteName }}</span>
                      </div>
                    </div>
                  </div>
                  <div class="device-status">
                    <el-tag :type="getDeviceStatusTag(device.deviceStatus)" size="small">
                      {{ getDeviceStatusText(device.deviceStatus) }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 设备详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="detailTitle" width="900px" :before-close="handleCloseDetailDialog">
      <div v-if="currentDetail" class="device-detail">
        <el-tabs v-model="activeDetailTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="设备ID">{{ currentDetail.deviceId }}</el-descriptions-item>
              <el-descriptions-item label="设备名称">{{ currentDetail.deviceName }}</el-descriptions-item>
              <el-descriptions-item label="设备IP">{{ currentDetail.deviceIp }}</el-descriptions-item>
              <el-descriptions-item label="所属站点">{{ currentDetail.siteName }}</el-descriptions-item>
              <el-descriptions-item label="设备状态">
                <el-tag :type="getDeviceStatusTag(currentDetail.deviceStatus)" size="small">
                  {{ getDeviceStatusText(currentDetail.deviceStatus) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="门禁状态">
                <el-tag :type="getAccessStatusTag(currentDetail.accessStatus)" size="small">
                  {{ getAccessStatusText(currentDetail.accessStatus) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDateTime(currentDetail.createTime) }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{ formatDateTime(currentDetail.updateTime) }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <el-tab-pane label="实时视频" name="live">
            <div class="live-video-section">
              <div class="video-player-large">
                <!-- <video-player v-if="currentDetail.liveStream" :src="currentDetail.liveStream.streamUrl"
                  class="large-video" :poster="getDevicePoster(currentDetail)" controls :loop="true" :volume="0.6" /> -->
                <LivePlayer v-if="currentDetail.liveStream" :src="currentDetail.liveStream.streamUrl" protocol="mp4"
                  :autoplay="true" :controls="true" />
                <div v-else class="no-stream">
                  <el-empty description="暂无实时视频流" :image-size="100" />
                  <el-button type="primary" @click="loadDeviceStreams(currentDetail)">
                    加载视频流
                  </el-button>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="事件记录" name="events">
            <div class="events-section">
              <div class="events-filter">
                <el-form :inline="true" :model="eventsFilter">
                  <el-form-item label="时间范围">
                    <el-date-picker v-model="eventsFilter.dateRange" type="daterange" range-separator="至"
                      start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
                  </el-form-item>
                  <el-form-item label="事件类型">
                    <el-select v-model="eventsFilter.eventType" placeholder="选择事件类型" clearable>
                      <el-option label="门禁开启" :value="1" />
                      <el-option label="门禁关闭" :value="2" />
                      <el-option label="异常报警" :value="3" />
                      <el-option label="设备离线恢复" :value="4" />
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="loadDeviceEvents">查询</el-button>
                  </el-form-item>
                </el-form>
              </div>

              <div class="events-list">
                <el-table :data="deviceEvents" v-loading="eventsLoading">
                  <el-table-column prop="eventTime" label="时间" width="160">
                    <template #default="{ row }">
                      {{ formatDateTime(row.eventTime) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="eventType" label="事件类型" width="120">
                    <template #default="{ row }">
                      <el-tag :type="getEventTypeTag(row.eventType)" size="small">
                        {{ getEventTypeText(row.eventType) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="eventDesc" label="事件描述" show-overflow-tooltip />
                  <el-table-column prop="eventStatus" label="处理状态" width="100">
                    <template #default="{ row }">
                      <el-tag :type="getEventStatusTag(row.eventStatus)" size="small">
                        {{ getEventStatusText(row.eventStatus) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="历史视频" name="history">
            <div class="history-section">
              <div class="history-filter">
                <el-form :inline="true" :model="historyFilter">
                  <el-form-item label="开始时间">
                    <el-date-picker v-model="historyFilter.startTime" type="datetime" placeholder="选择开始时间"
                      value-format="YYYY-MM-DD HH:mm:ss" />
                  </el-form-item>
                  <el-form-item label="结束时间">
                    <el-date-picker v-model="historyFilter.endTime" type="datetime" placeholder="选择结束时间"
                      value-format="YYYY-MM-DD HH:mm:ss" />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="loadHistoryStreams">查询</el-button>
                  </el-form-item>
                </el-form>
              </div>

              <div class="history-list">
                <el-table :data="historyStreams" v-loading="historyLoading">
                  <el-table-column prop="startTime" label="开始时间" width="160">
                    <template #default="{ row }">
                      {{ formatDateTime(row.startTime) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="endTime" label="结束时间" width="160">
                    <template #default="{ row }">
                      {{ formatDateTime(row.endTime) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="fileSize" label="文件大小" width="100">
                    <template #default="{ row }">
                      {{ formatFileSize(row.fileSize) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="videoFormat" label="格式" width="80" />
                  <el-table-column prop="storageStatus" label="存储状态" width="100">
                    <template #default="{ row }">
                      <el-tag :type="getStorageStatusTag(row.storageStatus)" size="small">
                        {{ getStorageStatusText(row.storageStatus) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120">
                    <template #default="{ row }">
                      <el-button type="primary" link size="small" @click="handlePlayHistory(row)">
                        播放
                      </el-button>
                      <el-button type="info" link size="small" @click="handleDownloadHistory(row)">
                        下载
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <template #footer>
        <el-button @click="handleCloseDetailDialog">关闭</el-button>
        <el-button type="primary" @click="handleAddToScreen" v-if="currentDetail">
          添加到分屏
        </el-button>
      </template>
    </el-dialog>

    <!-- 全屏播放对话框 -->
    <el-dialog v-model="fullScreenDialogVisible" :title="fullScreenTitle" width="95%" top="2vh"
      :before-close="handleCloseFullScreen">
      <div v-if="fullScreenDevice" class="full-screen-player">
        <!-- <video-player :src="fullScreenDevice.liveStream?.streamUrl" class="full-video"
          :poster="getDevicePoster(fullScreenDevice)" controls :loop="true" :volume="0.6" /> -->
        <LivePlayer :src="fullScreenDevice.liveStream?.streamUrl" protocol="mp4" :autoplay="true" :controls="true" />
      </div>
      <template #footer>
        <el-button @click="handleCloseFullScreen">退出全屏</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import LivePlayer from '@/components/LivePlayer'
import {
  getSiteTreeList,
  getAccessDeviceList,
  getAccessDeviceDetail,
  getAccessEventList,
  getLiveStreamList,
  getHistoryStreamList
} from '@/api/park/split_screen'

// 图标引入
import {
  Refresh,
  Expand,
  Fold,
  Search,
  VideoCamera,
  View,
  FullScreen,
  Close,
  Plus,
  MagicStick,
  Location,
  OfficeBuilding,
  SetUp
} from '@element-plus/icons-vue'

// 响应式数据
const treeRef = ref(null)
const treeFilterText = ref('')
const deviceFilterText = ref('')

// 站点树数据
const siteTreeData = ref([])
const allDevices = ref([])
const currentDevices = ref([])
const loading = ref(false)

// 分屏模式
const screenMode = ref(4) // 1, 4, 9, 16
const currentDevice = ref(null)
const currentDetail = ref(null)
const fullScreenDevice = ref(null)

// 对话框控制
const detailDialogVisible = ref(false)
const fullScreenDialogVisible = ref(false)
const activeDetailTab = ref('basic')

// 筛选数据
const eventsFilter = reactive({
  dateRange: [],
  eventType: ''
})

const historyFilter = reactive({
  startTime: dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
  endTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
})

// 详情数据
const deviceEvents = ref([])
const historyStreams = ref([])
const eventsLoading = ref(false)
const historyLoading = ref(false)

// 树形配置
const treeProps = {
  children: 'children',
  label: 'siteName'
}

// 计算属性
const filteredDevices = computed(() => {
  if (!deviceFilterText.value) {
    return allDevices.value
  }
  return allDevices.value.filter(device =>
    device.deviceName.toLowerCase().includes(deviceFilterText.value.toLowerCase()) ||
    device.deviceIp.includes(deviceFilterText.value)
  )
})

const detailTitle = computed(() => {
  return currentDetail.value ? `${currentDetail.value.deviceName} - 设备详情` : '设备详情'
})

const fullScreenTitle = computed(() => {
  return fullScreenDevice.value ? `${fullScreenDevice.value.deviceName} - 全屏播放` : '全屏播放'
})

// 初始化数据
onMounted(() => {
  initData()
})

const initData = async () => {
  try {
    loading.value = true
    await Promise.all([
      loadSiteTree(),
      loadAllDevices()
    ])
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 加载站点树
const loadSiteTree = async () => {
  try {
    const res = await getSiteTreeList()
    siteTreeData.value = res.data || []
  } catch (error) {
    console.error('加载站点树失败:', error)
    ElMessage.error('加载站点树失败')
  }
}

// 加载所有设备
const loadAllDevices = async () => {
  try {
    const res = await getAccessDeviceList()
    allDevices.value = res.data || []
    // 为设备添加站点名称
    allDevices.value.forEach(device => {
      const site = findSiteById(device.siteId)
      device.siteName = site ? site.siteName : '未知站点'
    })
  } catch (error) {
    console.error('加载设备列表失败:', error)
    ElMessage.error('加载设备列表失败')
  }
}

// 根据站点ID查找站点
const findSiteById = (siteId) => {
  const findInTree = (nodes) => {
    for (const node of nodes) {
      if (node.siteId === siteId) {
        return node
      }
      if (node.children && node.children.length > 0) {
        const found = findInTree(node.children)
        if (found) return found
      }
    }
    return null
  }
  return findInTree(siteTreeData.value)
}

// 树节点点击事件
const handleNodeClick = async (data) => {
  if (data.siteLevel === 3) { // 站点级节点
    try {
      loading.value = true
      const res = await getAccessDeviceList({ siteId: data.siteId })
      allDevices.value = res.data || []
      allDevices.value.forEach(device => {
        device.siteName = data.siteName
      })
    } catch (error) {
      console.error('加载站点设备失败:', error)
    } finally {
      loading.value = false
    }
  }
}

// 切换分屏模式
const changeScreenMode = (mode) => {
  screenMode.value = mode
  // 如果当前设备数量超过新模式，移除多余的设备
  if (currentDevices.value.length > mode) {
    currentDevices.value = currentDevices.value.slice(0, mode)
  }
}

// 智能排布
const autoArrange = () => {
  // 根据设备状态和重要性自动排布
  const onlineDevices = allDevices.value.filter(d => d.deviceStatus === 1)
  const importantDevices = onlineDevices.slice(0, screenMode.value)
  currentDevices.value = importantDevices

  // 为每个设备加载视频流
  currentDevices.value.forEach(device => {
    loadDeviceStreams(device)
  })

  ElMessage.success(`已智能排布 ${importantDevices.length} 个设备`)
}

// 添加设备到分屏
const handleToggleDevice = (device) => {
  const index = currentDevices.value.findIndex(d => d.deviceId === device.deviceId)
  if (index > -1) {
    // 如果设备已在分屏中，移除它
    currentDevices.value.splice(index, 1)
    ElMessage.info(`已从分屏移除: ${device.deviceName}`)
  } else {
    // 如果分屏已满，提示用户
    if (currentDevices.value.length >= screenMode.value) {
      ElMessage.warning(`分屏已满，最多支持 ${screenMode.value} 个设备`)
      return
    }
    // 添加设备到分屏
    currentDevices.value.push(device)
    // 加载设备视频流
    loadDeviceStreams(device)
    ElMessage.success(`已添加到分屏: ${device.deviceName}`)
  }
}

// 加载设备视频流
const loadDeviceStreams = async (device) => {
  try {
    const res = await getLiveStreamList(device.deviceId)
    if (res.data && res.data.length > 0) {
      device.liveStream = res.data[0] // 取第一个流
    } else {
      device.liveStream = null
    }
  } catch (error) {
    console.error('加载视频流失败:', error)
    device.liveStream = null
  }
}

// 查看设备详情
const handleViewDetail = async (device) => {
  try {
    const res = await getAccessDeviceDetail(device.deviceId)
    currentDetail.value = res.data
    detailDialogVisible.value = true
    // 加载详情相关数据
    await Promise.all([
      loadDeviceEvents(),
      loadHistoryStreams()
    ])
  } catch (error) {
    console.error('获取设备详情失败:', error)
    ElMessage.error('获取设备详情失败')
  }
}

// 加载设备事件
const loadDeviceEvents = async () => {
  if (!currentDetail.value) return

  try {
    eventsLoading.value = true
    const params = {
      deviceId: currentDetail.value.deviceId
    }

    if (eventsFilter.dateRange && eventsFilter.dateRange.length === 2) {
      params.startTime = eventsFilter.dateRange[0]
      params.endTime = eventsFilter.dateRange[1]
    }

    if (eventsFilter.eventType) {
      params.eventType = eventsFilter.eventType
    }

    const res = await getAccessEventList(params)
    deviceEvents.value = res.data || []
  } catch (error) {
    console.error('加载设备事件失败:', error)
  } finally {
    eventsLoading.value = false
  }
}

// 加载历史视频流
const loadHistoryStreams = async () => {
  if (!currentDetail.value) return

  try {
    historyLoading.value = true
    const res = await getHistoryStreamList(currentDetail.value.deviceId)
    historyStreams.value = res.data || []
  } catch (error) {
    console.error('加载历史视频流失败:', error)
  } finally {
    historyLoading.value = false
  }
}

// 全屏播放
const handleFullScreen = (device) => {
  fullScreenDevice.value = device
  fullScreenDialogVisible.value = true
}

// 移除分屏设备
const handleRemoveScreen = (device) => {
  const index = currentDevices.value.findIndex(d => d.deviceId === device.deviceId)
  if (index > -1) {
    currentDevices.value.splice(index, 1)
    ElMessage.info(`已从分屏移除: ${device.deviceName}`)
  }
}

// 添加空屏位
const handleAddScreen = () => {
  ElMessage.info('请从设备列表中选择要添加的设备')
}

// 添加到分屏
const handleAddToScreen = () => {
  if (currentDetail.value) {
    handleToggleDevice(currentDetail.value)
    detailDialogVisible.value = false
  }
}

// 播放历史视频
const handlePlayHistory = (stream) => {
  ElMessage.info(`播放历史视频: ${stream.startTime} - ${stream.endTime}`)
}

// 下载历史视频
const handleDownloadHistory = (stream) => {
  ElMessage.info(`下载历史视频: ${stream.startTime} - ${stream.endTime}`)
}

// 视频播放器事件
const handlePlayerReady = (device, player) => {
  console.log(`设备 ${device.deviceName} 播放器已就绪`, player)
}

const handlePlayerError = (device, error) => {
  console.error(`设备 ${device.deviceName} 播放器错误:`, error)
  ElMessage.error(`设备 ${device.deviceName} 视频播放失败`)
}

// 工具函数
const getNodeIcon = (data) => {
  if (data.siteLevel === 1) return 'Location'
  if (data.siteLevel === 2) return 'OfficeBuilding'
  return 'SetUp'
}

const getSiteStatusTag = (status) => {
  return status === 1 ? 'success' : 'danger'
}

const getSiteStatusText = (status) => {
  return status === 1 ? '启用' : '禁用'
}

const getDeviceStatusTag = (status) => {
  return status === 1 ? 'success' : 'danger'
}

const getDeviceStatusText = (status) => {
  return status === 1 ? '在线' : '离线'
}

const getAccessStatusTag = (status) => {
  return status === 1 ? 'success' : 'warning'
}

const getAccessStatusText = (status) => {
  return status === 1 ? '开启' : '关闭'
}

const getEventTypeTag = (type) => {
  const types = {
    1: 'success', // 门禁开启
    2: 'info',    // 门禁关闭
    3: 'danger',  // 异常报警
    4: 'warning'  // 设备离线恢复
  }
  return types[type] || 'info'
}

const getEventTypeText = (type) => {
  const types = {
    1: '门禁开启',
    2: '门禁关闭',
    3: '异常报警',
    4: '设备离线恢复'
  }
  return types[type] || '未知事件'
}

const getEventStatusTag = (status) => {
  return status === 1 ? 'success' : 'warning'
}

const getEventStatusText = (status) => {
  return status === 1 ? '已处理' : '未处理'
}

const getStorageStatusTag = (status) => {
  const statusMap = {
    0: 'warning',
    1: 'success',
    2: 'info'
  }
  return statusMap[status] || 'info'
}

const getStorageStatusText = (status) => {
  const statusMap = {
    0: '待存储',
    1: '已存储',
    2: '已删除'
  }
  return statusMap[status] || status || '-'
}

const getDevicePoster = (device) => {
  // 根据设备状态生成不同的占位图
  if (device.deviceStatus === 0) {
    return '/images/device-offline.jpg'
  }
  if (device.accessStatus === 0) {
    return '/images/access-closed.jpg'
  }
  return '/images/device-default.jpg'
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-'
  try {
    return dayjs(dateTimeString).format('YYYY-MM-DD HH:mm:ss')
  } catch {
    return dateTimeString
  }
}

const formatFileSize = (bytes) => {
  if (!bytes) return '-'
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
}

// 树搜索
const filterNode = (value, data) => {
  if (!value) return true
  return data.siteName.toLowerCase().includes(value.toLowerCase())
}

// 刷新树
const refreshTree = () => {
  loadSiteTree()
  ElMessage.success('站点树已刷新')
}

// 展开所有节点
const expandAll = () => {
  treeRef.value?.store?.nodesMap?.forEach(node => {
    node.expanded = true
  })
}

// 折叠所有节点
const collapseAll = () => {
  treeRef.value?.store?.nodesMap?.forEach(node => {
    node.expanded = false
  })
}

// 关闭对话框
const handleCloseDetailDialog = () => {
  detailDialogVisible.value = false
  currentDetail.value = null
}

const handleCloseFullScreen = () => {
  fullScreenDialogVisible.value = false
  fullScreenDevice.value = null
}
</script>

<style scoped lang="scss">
.page-header {
  margin-bottom: 20px;
  text-align: center;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.main-content {
  display: flex;
  flex: 1;
  gap: 20px;
  min-height: 0;
}

.left-sidebar {
  width: 100%;
  flex-shrink: 0;
}

.right-content {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.tree-card,
.mode-card,
.device-list-card {
  height: auto;
}

.tree-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .tree-search {
    border-bottom: 1px solid #f0f0f0;
  }

  .tree-container {
    height: 400px;
    overflow-y: auto;
    margin-top: 20px;
  }
}

.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 4px 0;
}

.node-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-icon {
  color: #409EFF;
  font-size: 16px;
}

.node-label {
  font-size: 14px;
  color: #303133;
}

.node-count {
  font-size: 12px;
  color: #909399;
}

.node-status {
  margin-left: auto;
}

.mode-card {
  .mode-selection {
    display: flex;
    align-items: center;
    gap: 20px;
  }

  .mode-title {
    font-weight: 600;
    color: #303133;
  }

  .screen-info {
    margin-left: auto;
    display: flex;
    align-items: center;
    gap: 10px;
    color: #909399;
    font-size: 14px;
  }
}

.screen-container {
  display: grid;
  gap: 10px;
  flex: 1;
  min-height: 0;

  &.screen-mode-1 {
    grid-template-columns: 1fr;
    grid-template-rows: 1fr;
  }

  &.screen-mode-4 {
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
  }

  &.screen-mode-9 {
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr;
  }

  &.screen-mode-16 {
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr 1fr;
  }
}

.screen-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  min-height: 200px;
  background: white;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;

  &:hover {
    border-color: #409EFF;
    box-shadow: 0 2px 12px rgba(64, 158, 255, 0.1);
  }

  &.active {
    border-color: #409EFF;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }

  &.empty {
    border-style: dashed;
    background: #fafafa;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background: #f0f9ff;
      border-color: #409EFF;
    }

    .empty-content {
      text-align: center;
      color: #909399;

      .empty-icon {
        font-size: 32px;
        margin-bottom: 8px;
      }

      .empty-text {
        margin: 0;
        font-size: 14px;
      }
    }
  }
}

.screen-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #fafafa;
  border-bottom: 1px solid #e4e7ed;
}

.device-info {
  .device-name {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
    color: #303133;
  }

  .device-status {
    display: flex;
    gap: 4px;
    margin-top: 2px;
  }
}

.screen-actions {
  display: flex;
  gap: 4px;
}

.video-container {
  flex: 1;
  position: relative;
  background: #000;
}

.video-player {
  width: 100%;
  height: 100%;
}

.video-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;

  .placeholder-content {
    text-align: center;

    .placeholder-icon {
      font-size: 48px;
      margin-bottom: 8px;
    }

    .placeholder-text {
      margin: 0 0 12px 0;
      font-size: 14px;
    }
  }
}

.screen-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #fafafa;
  border-top: 1px solid #e4e7ed;
}

.device-meta {
  display: flex;
  gap: 8px;
  font-size: 12px;
  color: #909399;
}

.device-list-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .device-list {
    max-height: 200px;
    overflow-y: auto;
  }
}

.device-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border: 1px solid transparent;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background: #f5f7fa;
    border-color: #e4e7ed;
  }

  &.active {
    background: #ecf5ff;
    border-color: #409EFF;
  }

  .device-main {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .device-icon {
    color: #409EFF;
  }

  .device-info {
    .device-name {
      font-weight: 500;
      color: #303133;
      margin: 0;
    }

    .device-details {
      display: flex;
      gap: 8px;
      font-size: 12px;
      color: #909399;
      margin-top: 2px;
    }
  }
}

.device-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.live-video-section {
  .video-player-large {
    height: 400px;
    background: #000;
    border-radius: 4px;
    overflow: hidden;
  }

  .no-stream {
    text-align: center;
    padding: 40px 0;
  }
}

.events-section,
.history-section {

  .events-filter,
  .history-filter {
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #e4e7ed;
  }
}

.full-screen-player {
  .full-video {
    width: 100%;
    height: 70vh;
  }
}
</style>